package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.admin.SetmealDishMapper;
import com.sky.mapper.admin.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.admin.SetmealService;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

//    private final SetmealMapper setmealMapper;
//    private final SetmealDishMapper setmealDishMapper;
//
//    public SetmealServiceImpl(SetmealMapper setmealMapper, SetmealDishMapper setmealDishMapper) {
//        this.setmealMapper = setmealMapper;
//        this.setmealDishMapper = setmealDishMapper;
//    }

    /**
     * 套餐分页查询
     *
     * @param setmealPageQueryDTO
     * @return
     */
    @Override
    public PageResult selectPage(SetmealPageQueryDTO setmealPageQueryDTO) {
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());
        Page<SetmealVO> selectPage =  setmealMapper.selectPage(setmealPageQueryDTO);
        log.info(String.valueOf(selectPage));
        return new PageResult(selectPage.getTotal(), selectPage.getResult());
    }

    /**
     * 新增套餐
     *
     * @param setmealDTO
     */

    @Transactional
    @Override
    public void insert(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        Long currentId = BaseContext.getCurrentId();
        setmeal.setCreateUser(currentId);

        // 插入记录
        setmealMapper.insert(setmeal);

        // 从 `setmeal` 对象中获取生成的主键值
        Long setmealId = setmeal.getId();
        log.info("获取到的套餐id为{}", setmealId);

        List<SetmealDish> setmealDishesList = setmealDTO.getSetmealDishes();
        if (setmealDishesList != null && !setmealDishesList.isEmpty()) {    // 不为空的情况下
            for (SetmealDish setmealDish : setmealDishesList) {     // 遍历菜单套餐表

                setmealDish.setSetmealId(setmealId);
                log.info("进行打印套餐菜单表{}", setmealDish);
                setmealDishMapper.insertBatch(setmealDish); // 批量插入操作
            }

        }
    }

    /**
     * 批量删除套餐
     *
     * @param ids
     */
    @Transactional
    @Override
    public void deleteBatch(ArrayList<Long> ids) {

        // 检查传入的id集合是否为空
        if (ObjectUtils.isEmpty(ids)) {
            throw new DeletionNotAllowedException(MessageConstant.NULL_CHOICE);
        }

        // 过滤满足删除条件的id集合
        List<Long> idsToDelete = ids.stream()
                .filter(id -> {
                    SetmealVO setmealVO = selectById(id);
                    return setmealVO != null && setmealVO.getStatus() == StatusConstant.DISABLE;
                })
                .collect(Collectors.toList());

        // 检查过滤后的可删除id集合是否为空
        if (ObjectUtils.isEmpty(idsToDelete)) {
            throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
        }

        log.info("过滤后的id集合为: {}", idsToDelete);

        // 执行删除操作
        try {
            setmealMapper.deleteBatch(idsToDelete);
            setmealDishMapper.deleteBatch(idsToDelete);
        } catch (BadSqlGrammarException e) {
            log.error("删除操作异常: {}", e.getMessage());
            throw new DeletionNotAllowedException(MessageConstant.NULL_CHOICE);
        }
    }





    /**
     * 套餐id回显
     *
     * @param id
     * @return
     */
    @Override
    public SetmealVO selectById(Long id) {

        SetmealVO setmealVO = new SetmealVO();
        Setmeal setmeal = setmealMapper.selectById(id);
        BeanUtils.copyProperties(setmeal, setmealVO);

        List<SetmealDish> setmealDishes = setmealDishMapper.selectBatch(id);// 根据id获取菜品套餐
        log.info("获取到的套餐菜品集合为{}",setmealDishes);
        setmealVO.setSetmealDishes(setmealDishes);




        return setmealVO;
    }

    /**
     * 修改套餐
     *
     * @param setmealDTO
     */
    @Transactional
    @Override
    public void update(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        setmealMapper.update(setmeal);
        setmealDishMapper.deleteBatch(Collections.singletonList(setmeal.getId()));
        if (!CollectionUtils.isEmpty(setmealDTO.getSetmealDishes())){

            for (SetmealDish setmealDish : setmealDTO.getSetmealDishes()) {
                log.info("更新操作获取到的套餐菜品为{}",setmealDish);
                setmealDish.setSetmealId(setmealDTO.getId());
                setmealDishMapper.insertBatch(setmealDish);
            }

        }
    }

    /**
     * 套餐起售停售
     *
     * @param status
     * @param id
     */
    @Override
    public void status(Long status, Long id) {
        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .build();
        log.info("套餐更新状态{}", setmeal);
        setmealMapper.status(setmeal);
    }


}
